/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormAberturaComanda.java
 *
 * Created on 05/05/2013, 23:27:14
 */
package forms;

import classes.Conexao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Jonatas
 */
public class FormAberturaMesa extends javax.swing.JInternalFrame {

    /**
     * Creates new form FormAberturaComanda
     */
    public FormAberturaMesa() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        jLabelComanda = new javax.swing.JLabel();
        jButtonAbrir = new javax.swing.JButton();
        jComboBoxComanda = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableMesa = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxMesa = new javax.swing.JComboBox();

        setClosable(true);
        setIconifiable(true);
        setTitle("Abertura de Mesa");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener()
        {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt)
            {
                formInternalFrameOpened(evt);
            }
        });

        jLabelComanda.setText("Mesa:");

        jButtonAbrir.setText("Abrir");
        jButtonAbrir.setToolTipText("Clique aqui para abrir");
        jButtonAbrir.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonAbrirActionPerformed(evt);
            }
        });

        jComboBoxComanda.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jTableMesa.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][]
            {

            },
            new String []
            {
                "Mesas em Uso", "Data e Hora de Abertura", "Comanda"
            }
        )
        {
            Class[] types = new Class []
            {
                java.lang.String.class, java.lang.Object.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean []
            {
                false, false, false
            };

            public Class getColumnClass(int columnIndex)
            {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex)
            {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTableMesa);
        jTableMesa.getColumnModel().getColumn(1).setPreferredWidth(100);

        jLabel1.setText("Comanda:");

        jComboBoxMesa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabelComanda))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jComboBoxComanda, 0, 65, Short.MAX_VALUE)
                            .addComponent(jComboBoxMesa, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(27, 27, 27)
                        .addComponent(jButtonAbrir, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelComanda)
                    .addComponent(jButtonAbrir)
                    .addComponent(jComboBoxMesa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBoxComanda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-396)/2, (screenSize.height-307)/2, 396, 307);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAbrirActionPerformed
        //Pega o numero da comanda e converte para int
        int c = Integer.parseInt(jComboBoxComanda.getSelectedItem().toString());
        int m = Integer.parseInt(jComboBoxMesa.getSelectedItem().toString());
        //Pega a hora do sistema para inserir no banco
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        System.out.println(sdf.format(new Date()));
        
        try 
        {
            String sql = "INSERT INTO ABERTURA_MESA VALUES (abertura_mesa_seq.nextval,sysdate,null,null," + c + "," + m + ")";

            if (Conexao.atualizar(sql) != -1) {
                //JOptionPane.showMessageDialog(null, "Cadastrado com sucesso.", "Cadastro", 1);
            } else {
                JOptionPane.showMessageDialog(null, Conexao.getErro(), "Cadastro", 1);
            }
            pesquisarTudo();
            atualizarTabela();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Erro: \n" + e.getMessage(), "Erro!", 0);
        }

    }//GEN-LAST:event_jButtonAbrirActionPerformed

    //Executa essas instruções ao abrir o internalFrame
    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened

        try {
            pesquisarTudo();
            atualizarTabela();

        } catch (SQLException ex) {
            Logger.getLogger(FormAberturaMesa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formInternalFrameOpened

   private HashMap<Integer, Integer> comandas = new HashMap<Integer, Integer>();

    private void pesquisarTudo() {
        DefaultComboBoxModel model2 = (DefaultComboBoxModel) jComboBoxComanda.getModel();
        model2.removeAllElements();
        DefaultComboBoxModel modelo2 = (DefaultComboBoxModel) jComboBoxMesa.getModel();
        modelo2.removeAllElements();//para cada vez que executar isso, limpar as linhas da tabela

        try {

            //Pega o código de abertura comanda na tabela Abertura Comanda que não esteja em uso
            String sqlAbertComa ="select * from ABERTURA_COMANDA where \"cd_comanda\" not in(select \"cd_comanda\" from "
                    + "ABERTURA_MESA where \"dt_hora_fechar\" is null) ORDER BY \"cd_comanda\"";
            
            ResultSet rs1 = Conexao.consultar(sqlAbertComa);

            comandas.clear();
            while (rs1.next()) {
                comandas.put(rs1.getInt("cd_comanda"), rs1.getInt("cd_abertura_comanda"));
                model2.addElement(rs1.getInt("cd_comanda"));
            }
            String sql = "select * from MESA where \"CD_MESA\" not in(select \"cd_mesa\" from ABERTURA_MESA where \"dt_hora_fechar\" is null) ORDER BY \"CD_MESA\"";

            ResultSet res2 = Conexao.consultar(sql);

            if (Conexao.consultar(sql) == null) {
                JOptionPane.showMessageDialog(null, "Erro na consulta:\n" + Conexao.getErro(), "Erro!", 0);
            } else {
                while (res2.next()) {
                    modelo2.addElement(
                            res2.getInt("CD_MESA"));
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Erro na consulta: \n" + e.getMessage(), "Erro!", 0);
        }
    }

    private void atualizarTabela() throws SQLException {
        DefaultTableModel tableModel = (DefaultTableModel) jTableMesa.getModel();
        tableModel.setRowCount(0);

        String sqlAbertMesa =
                "SELECT * "
                + "FROM \"ABERTURA_MESA\" "
                + "WHERE \"ABERTURA_MESA\".\"dt_hora_fechar\" is null "
                + "ORDER BY \"cd_mesa\"";

        ResultSet rs1 = Conexao.consultar(sqlAbertMesa);
        int mesa = 0;

        SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        //System.out.println("Teste formato data: " + dt.format(new Date()));
        while (rs1.next()) {
            tableModel.addRow(new Object[]{
                        mesa = rs1.getInt("cd_mesa"),
                        dt.format(rs1.getTimestamp("dt_hora_abertura")),
                        rs1.getInt("cd_comanda")
                    });
        }

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAbrir;
    private javax.swing.JComboBox jComboBoxComanda;
    private javax.swing.JComboBox jComboBoxMesa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabelComanda;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableMesa;
    // End of variables declaration//GEN-END:variables
}
